<?php

// +----------------------------------------------------------------------
// | B5LaravelCMF V2.0 [快捷通用基础管理开发平台]
// +----------------------------------------------------------------------
// | Author: 冰舞 <357145480@qq.com>
// +----------------------------------------------------------------------
declare(strict_types=1);

namespace App\Http\Controllers\Admin\Xs;

use App\Extends\Helpers\Admin\LoginAuth;
use App\Extends\Helpers\Result;
use App\Extends\Libs\AdminCommonAction;
use App\Extends\Validates\Xs\UserValidate;
use App\Models\Xs\XsUser;
use Illuminate\Contracts\View\View;
use Illuminate\Http\JsonResponse;

class XsUserController extends Xs
{
    use AdminCommonAction;

    protected string $model = XsUser::class;
    protected string $validate = UserValidate::class;

    /**
     * 首页渲染
     *
     * @return View
     */
    protected function indexRender(): View
    {
        return $this->render('', ['is_admin' => LoginAuth::adminLoginInfo('info.is_admin')]);
    }

    public function add(): View|JsonResponse
    {
        if ($this->request->isMethod('POST')) {
            $data = $this->request->post();
            // 验证
            if ($this->validate ?? false) {
                // 验证前数据处理
                $data = $this->validateBefore($data, 'add');
                if (!is_array($data)) {
                    return Result::error($data);
                }
                $error = (new $this->validate())->setScene('add')->setData($data)->run();
                if ($error) {
                    return Result::error($error);
                }
            }

            $userInfo = LoginAuth::adminLoginInfo();
            $uid = $userInfo['info']['id'] ?? 0;
            $mobiles = $data['mobile'];
            $note = $data['note'];

            $arrayMobiles = (explode("\n", $mobiles));

            $insertData = [];
            foreach ($arrayMobiles as $mobile) {
                $mobile = str_replace("\r", '', trim($mobile));

                if (!preg_match('/^1[3456789]\d{9}$/', $mobile)) {
                    return Result::error('请输入正确的手机号：【' . $mobile . '】');
                }

                if (XsUser::query()->where('uid', '>', 0)->where('uid', '<>', $uid)->where('mobile', $mobile)->exists()) {
                    return Result::error('此手机号【' . $mobile . '】已被绑定');
                }

                // 如果未绑定，就绑定过来
                $model = XsUser::query()->where('uid', 0)->where('mobile', $mobile)->first();
                if ($model) {
                    $model->uid = $uid;
                    $model->note = $note;
                    $model->save();
                } else {
                    $insertData[] = [
                        'mobile' => $mobile,
                        'note' => $note,
                        'uid' => $uid,
                        'create_time' => date('Y-m-d H:i:s'),
                        'update_time' => date('Y-m-d H:i:s'),
                    ];
                }
            }

            if ($insertData) {
                XsUser::query()->insert($insertData);
            }

            return Result::success('录入成功');
        } else {
            return $this->addRender();
        }
    }

    /**
     * 首页列表查询前条件处理
     *
     * @param array $params
     *
     * @return array
     */
    protected function indexBefore(array $params): array
    {
        $userInfo = LoginAuth::adminLoginInfo();

        if ($userInfo['info']['is_admin']) {
            return $params;
        }
        $uid = $userInfo['info']['id'] ?? 0;
        $params['where']['uid'] = (string) $uid;

        return $params;
    }

    protected function editRender(array $info): View
    {
        return $this->render('', ['info' => $info, 'is_admin' => LoginAuth::adminLoginInfo('info.is_admin')]);
    }

    /**
     * 公共删除单条数据
     *
     * @return JsonResponse
     */
    public function drop(): JsonResponse
    {
        if ($this->request->isMethod('POST')) {
            $id = $this->request->post('id', '');
            if (!$id) {
                return Result::error('参数缺失');
            }
            $info = $this->model::query()->findOrFail($id);
            if (!$info) {
                return Result::error('信息不存在或数据已删除');
            }

            $info->uid = 0;
            $info->note = '';
            $info->update_time = date('Y-m-d H:i:s');
            if ($info->save()) {
                return Result::success('删除成功');
            } else {
                return Result::success('删除成功');
            }
        }

        return Result::error('请求类型错误');
    }

    /**
     * 批量删除
     *
     * @return JsonResponse
     */
    public function dropall(): JsonResponse
    {
        if ($this->request->isMethod('POST')) {
            $ids = $this->request->post('ids', '');
            if (!$ids) {
                return Result::error('参数缺失');
            }
            $ids = explode(',', $ids);
            $num = 0;
            foreach ($ids as $id) {
                if (!$id) {
                    continue;
                }
                $info = $this->model::query()->findOrFail($id);

                $info->update_time = date('Y-m-d H:i:s');
                $info->uid = 0;
                $info->note = '';
                if ($info->save()) {
                    $num++;
                }
            }

            return Result::success('批量删除完成，共删除' . $num . '条记录');
        }

        return Result::error('请求类型错误');
    }
}
